package com.leviassaf.androidbasics;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class Tabs extends Activity implements OnClickListener, TabContentFactory {
	
	TabHost tabhost;
	int intTabIndex = 0;
	
	//87
	TextView txtResults;
	long lngStart, lngStop;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tabs);
		
		String strStopWatch = "Stop Watch";
		String strAddTab = "Add a tab";
		
		tabhost = (TabHost)findViewById(R.id.tabhost);
		tabhost.setup();
		
		//86
		Button btnStop = (Button)findViewById(R.id.btnStop);
		Button btnStart = (Button)findViewById(R.id.btnStart);
		Button btnAddTab = (Button)findViewById(R.id.btnAddTab);
		
		//87
		txtResults = (TextView)findViewById(R.id.txtResults);
		

		//Set listeners for the buttons
		btnStop.setOnClickListener(this);
		btnStart.setOnClickListener(this);
		btnAddTab.setOnClickListener(this);
		

		addTabToTabHost(tabhost, strStopWatch, R.id.tab1);
		addTabToTabHost(tabhost, "tag 2", R.id.tab2);
		addTabToTabHost(tabhost, strAddTab, R.id.tab3);
		
		//87
		lngStart = 0;

		this.setTitle(String.format("%s-%s", this.getTitle().toString(), this.getClass().getSimpleName()));
	}
	
	public void addTabToTabHost(TabHost Host, String TabName, int TabId){
		TabSpec tabspec = Host.newTabSpec(TabName);
		tabspec.setContent(TabId);
		tabspec.setIndicator(TabName);
		Host.addTab(tabspec);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		case R.id.btnStop:
			lngStop = System.currentTimeMillis();
			if (lngStart != 0){
				long lngResult = lngStop - lngStart;
				//88
				int intMillis = (int)lngResult;
				int intSeconds = (int)lngResult / 1000;
				int intMinutes = intSeconds / 60;
				intMillis = intMillis % 100;
				
				txtResults.setText(String.format("%02d:%02d:%02d", 
					intMinutes,
					intSeconds,
					intMillis)
				);
			}
			break;
		case R.id.btnStart:
			//87
			lngStart = System.currentTimeMillis();
			break;
		case R.id.btnAddTab:
			TabSpec tabspec = tabhost.newTabSpec("New " + intTabIndex);
			tabspec.setContent(this);
			intTabIndex++;
			tabspec.setIndicator("New " + intTabIndex);
			tabhost.addTab(tabspec);
			break;
		}
	}

	@Override
	public View createTabContent(String tag) {
		// TODO Auto-generated method stub
		TextView txtTabMessage = new TextView(this);
		txtTabMessage.setText(String.format("This tab was created at run-time"));
		return txtTabMessage;
	}

}
